# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

from scrapy.utils.project import get_project_settings
import pymysql

class ScrapyReadbookPipeline:
    def open_spider(self, spider):
        self.fp = open('book.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        self.fp.write(str(item))
        return item

    def close_spider(self, spider):
        self.fp.close()


class ScrapyReadbookWriteDBPipeline:
    def open_spider(self, spider):
        settings = get_project_settings()
        self.host = settings.get('DB_HOST')
        self.port = settings.get('DB_PORT')
        self.user = settings.get('DB_USER')
        self.password = settings.get('DB_PASSWORD')
        self.charset = settings.get('DB_CHARSET')
        self.db_name = settings.get('DB_NAME')
        self.connect()


    def connect(self):
        self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.password, db=self.db_name,
                                  charset=self.charset)
        self.corsor=self.conn.cursor()

    def process_item(self, item, spider):
        sql='insert into book_info (name,src) values ("{}","{}")'.format(item['name'],item['src'])
        self.corsor.execute(sql)
        self.conn.commit()



    def close_spider(self, spider):
        self.corsor.close()
        self.conn.close()

